from app.common.const import DEFAULT_LEN_LIMIT
from app.common.const import MAX_PAGE_LEN_LIMIT
from app.common.errors import ApiError
from app.common.errors import Error
from app.util.str_converters import snake_case


class TortoiseObjectType:
    """
    patch一下 graphql与tortoise-orm
    """

    class Meta:
        model = None
        name_mapping = {}

    @classmethod
    def get_model(cls):
        return cls.Meta.model

    @classmethod
    def get_name_mapping(cls) -> dict:
        return cls.Meta.name_mapping

    @classmethod
    def get_model_fields(cls):
        from tortoise.models import Model

        model: Model = cls.get_model()
        return set(model._meta.fields)

    @classmethod
    def load_model_field(cls, info):
        """
        目前主要解决数据库查询字段限制的问题，将请求的query数据转化为model上需要select的字段
        """
        select_fields = info.selected_fields[0].selections
        for field in select_fields:
            field_name = snake_case(field.name)
            if field_name in cls.get_name_mapping():
                yield from cls.get_name_mapping()[field_name]
            elif field_name in cls.get_model_fields():
                yield field_name


def query_to_connection_list(q, limit=DEFAULT_LEN_LIMIT, offset=0, after=None):
    if limit > MAX_PAGE_LEN_LIMIT:
        raise ApiError(Error.PAGINATE_LIMIT_ERROR, limit=MAX_PAGE_LEN_LIMIT)

    if offset > 0:
        q.skip(offset)

    if after is not None:
        q.greater_than("objectId", after)

    return q.limit(limit).find()


def default_resolver():
    return {}
